﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace ZJRM.KingdeeK3Cloud.PlugIn.KAndOSysSynLog
{
    [Description("金蝶和第三方同步日志报表插件")]
    [HotUpdate]
    public class ReportPlugInSyncLog : SysReportBaseService
    {
        private List<string> customRptTempTableNames;
        //初始化
        public override void Initialize()
        {
            base.Initialize();
            // 简单账表类型：普通、树形、分页
            this.ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            this.IsCreateTempTableByPlugin = true;
            //是否分组汇总
            this.ReportProperty.IsGroupSummary = true;
            //this.ReportProperty.PrimaryKeyFieldName = "FCUSTNUMBER";
        }

        //获取过滤条件信息(构造单据信息)
        public override ReportTitles GetReportTitles(IRptParams filter)
        {
            ReportTitles reportTitles = base.GetReportTitles(filter);
            return reportTitles;
        }

        //组织名称
        private string GetMultiOrgnNameValues(string orgIdStrings)
        {
            List<string> list = new List<string>();
            string result = string.Empty;

            if (orgIdStrings.Trim().Length > 0)
            {
                IQueryService service = Kingdee.BOS.Contracts.ServiceFactory.GetService<IQueryService>(base.Context);

                QueryBuilderParemeter para = new QueryBuilderParemeter
                {
                    FormId = "ORG_Organizations",
                    SelectItems = SelectorItemInfo.CreateItems("FNAME"),
                    FilterClauseWihtKey = string.Format(" FORGID IN ({0}) AND FLOCALEID={1}", orgIdStrings, base.Context.UserLocale.LCID)
                };
                DynamicObjectCollection dynamicObjectCollection = service.GetDynamicObjectCollection(base.Context, para, null);
                foreach (DynamicObject current in dynamicObjectCollection)
                {
                    list.Add(current["FNAME"].ToString());
                }
                if (list.Count > 0)
                {
                    result = string.Join(",", list.ToArray());
                }
            }
            return result;
        }

        //用户资料id
        private string GetUserDataIDValue(DynamicObjectCollection dyobj)
        {
            string name = "";
            if (dyobj == null)
            {
                return name;
            }
            foreach (DynamicObject dynbj in dyobj)
            {
                if (dynbj != null || !dynbj.DynamicObjectType.Properties.Contains("id"))
                {
                    DynamicObject dynbj2 = (DynamicObject)dynbj[2];
                    if (string.IsNullOrEmpty(name))
                    {
                        name = dynbj2["id"].ToString();
                    }
                    else
                    {
                        name = name + "," + dynbj2["id"].ToString();
                    }
                }
            }
            return name;
        }

        //基础资料名称
        private string GetBaseDataNameValue(DynamicObjectCollection dyobj)
        {
            string name = "";
            if (dyobj == null)
            {
                return name;
            }
            foreach (DynamicObject dynbj in dyobj)
            {
                if (dynbj != null || !dynbj.DynamicObjectType.Properties.Contains("Name"))
                {
                    DynamicObject dynbj2 = (DynamicObject)dynbj[2];
                    if (string.IsNullOrEmpty(name))
                    {
                        name = dynbj2["Name"].ToString();
                    }
                    else
                    {
                        name = name + "," + dynbj2["Name"].ToString();
                    }
                }
            }
            return name;
        }

        //基础资料id
        private string GetBaseDataIDValue(DynamicObjectCollection dyobj)
        {
            string name = "";
            if (dyobj == null)
            {
                return name;
            }
            foreach (DynamicObject dynbj in dyobj)
            {
                if (dynbj != null || !dynbj.DynamicObjectType.Properties.Contains("msterID"))
                {
                    DynamicObject dynbj2 = (DynamicObject)dynbj[2];
                    if (string.IsNullOrEmpty(name))
                    {
                        name = dynbj2["msterID"].ToString();
                    }
                    else
                    {
                        name = name + "," + dynbj2["msterID"].ToString();
                    }
                }
            }
            return name;
        }

        //基础资料名称
        private string GetBaseDataNameValue(DynamicObject dyobj)
        {
            string name = "";
            if (dyobj == null)
            {
                return name;
            }
            if (dyobj != null || !dyobj.DynamicObjectType.Properties.Contains("Name"))
            {
                name = dyobj["Name"].ToString();
            }
            return name;
        }

        //基础资料名称
        private string GetBaseDataIDValue(DynamicObject dyobj)
        {
            string name = "";
            if (dyobj == null)
            {
                return name;
            }
            if (dyobj != null || !dyobj.DynamicObjectType.Properties.Contains("msterID"))
            {
                name = dyobj["msterID"].ToString();
            }
            return name;
        }

        /// <summary>
        /// 设置单据列
        /// 二级标题不会显示多选框
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            ReportHeader header = new ReportHeader();
            #region           
            header.AddChild("FID", new LocaleValue("ID", this.Context.UserLocale.LCID), SqlStorageType.SqlBigInt);
            header.AddChild("OPERATION", new LocaleValue("操作名称", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FORMID", new LocaleValue("单据标识", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FBILLNO", new LocaleValue("单据编号", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FBILLNAME", new LocaleValue("单据名称", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FMODIFYDATE", new LocaleValue("创建日期", this.Context.UserLocale.LCID), SqlStorageType.SqlDatetime);
            header.AddChild("RESULT", new LocaleValue("同步结果", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("JSON", new LocaleValue("JSON数据", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("DIRECTION", new LocaleValue("同步方向", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FORGID", new LocaleValue("组织ID", this.Context.UserLocale.LCID), SqlStorageType.SqlBigInt);
            header.AddChild("FORGNAME", new LocaleValue("组织名称", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("IsSuccess", new LocaleValue("是否成功", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            #endregion

            return header;
        }

        //创建临时报表
        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;

            //多选组织
            DynamicObjectCollection mulOrgs = customFilter["FMulOrgIds"] as DynamicObjectCollection;
            string orgIds = GetUserDataIDValue(mulOrgs);

            //多选业务对象
            DynamicObjectCollection mulForms = customFilter["FMulFormIds"] as DynamicObjectCollection;
            string mulFormIds = GetUserDataIDValue(mulForms);

            //开始日期
            DateTime beginDate = Convert.ToDateTime(customFilter["FBeginDate"]);
            string beginDateStr = "";
            if (beginDate != null && beginDate != DateTime.MinValue)
            {
                beginDateStr = Convert.ToString(beginDate);
            }
            //结束日期
            DateTime endDate = Convert.ToDateTime(customFilter["FEndDate"]);
            string endDateStr = "";
            if (endDate != null && endDate != DateTime.MinValue)
            {
                endDateStr = Convert.ToString(endDate);
            }

            //编号
            string billNo = Convert.ToString(customFilter["FBillNo"]);

            //id
            long id = Convert.ToInt64(customFilter["FId"]);

            //同步结果
            string synResult = Convert.ToString(customFilter["FSynResult"]);

            //不显示JSON
            bool isShowJson = Convert.ToBoolean(customFilter["FIsShowJson"]);

            SqlParam[] sqlParams = new SqlParam[] {
                new SqlParam("@orgIds",KDDbType.String,orgIds),
                new SqlParam("@mulFormIds",KDDbType.String,mulFormIds),
                new SqlParam("@beginDate",KDDbType.String,beginDateStr),
                new SqlParam("@endDate",KDDbType.String,endDateStr),
                new SqlParam("@billNo",KDDbType.String,billNo),
                new SqlParam("@id",KDDbType.Int64,id),
                new SqlParam("@synResult",KDDbType.String,synResult)
            };
            string seqFld = string.Format(base.KSQL_SEQ, BuilderTempTableOrderBySQL(filter));
            string Filter = GetFilterWhere(filter);
            /**DECLARE @orgIds VARCHAR(max) = '';
DECLARE @mulFormIds VARCHAR(max) = '';
DECLARE @beginDate VARCHAR(max) = '';
DECLARE @endDate VARCHAR(max) = '';
DECLARE @billNo VARCHAR(max) = '';
DECLARE @id INT = '';
DECLARE @synResult VARCHAR(max) = '';
            **/
            string createTableSql = string.Format(@"/*dialect*/
            SELECT a.*,b.FNAME AS FOrgName  
into #temp
FROM dbo.T_Log_SyncLogs a
LEFT JOIN dbo.T_ORG_ORGANIZATIONS_L b ON b.FORGID = a.FOrgId AND b.FLOCALEID = {0}
WHERE 1=1 
AND (@orgIds = '' OR a.FOrgId IN (SELECT a1.FID  FROM dbo.fn_StrSplitLarge(@orgIds,',') a1))
AND (@mulFormIds = '' OR a.FormId IN (SELECT a1.FID  FROM dbo.fn_StrSplitLarge(@mulFormIds,',') a1))
AND (@beginDate='' OR a.FmodifyDate >= CONVERT(DATETIME,@beginDate))
AND (@endDate='' OR a.FmodifyDate < CONVERT(DATETIME,@endDate))
AND (@billNo='' OR a.FBillNo = @billNo)
AND (@id=0 OR a.FID = @id)
AND (@synResult='' OR a.Result LIKE '%' + @synResult +  '%')
", this.Context.UserLocale.LCID);


            string sqlEnd = string.Format("select *, {0} into {1} from #temp {2}", seqFld, tableName, Filter);
            string sql = createTableSql + sqlEnd;
            try
            {
                DBUtils.Execute(this.Context, sql, sqlParams);

            }
            catch (Exception er)
            {
                if (er.Message.Contains("对象名 'dbo.T_Log_SyncLogs' 无效"))
                {
                    //重新创建表
                    string sqlCreate = string.Format(@"/*dialect*/
                    CREATE TABLE [dbo].[T_Log_SyncLogs](
	                    [FID] [INT] IDENTITY(1,1) NOT NULL,
	                    [Operation] [VARCHAR](50) NULL,
	                    [FormId] [VARCHAR](100) NULL,
	                    [FBillNo] [VARCHAR](50) NULL,
	                    [FbillName] [VARCHAR](100) NULL,
	                    [FmodifyDate] [DATETIME] NULL,
	                    [Result] [VARCHAR](MAX) NULL,
	                    [Json] [VARCHAR](MAX) NULL,
	                    [Direction] [VARCHAR](50) NULL,
	                    [FOrgId] [INT] DEFAULT(0) NULL, 
                        [IsSuccess] [VARCHAR](255) NULL,
                        [errCount] [INT] NULL
                    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
                    ");
                    DBUtils.Execute(this.Context, sqlCreate);
                    DBUtils.Execute(this.Context, sql, sqlParams);
                }
                else
                {
                    throw er;
                }
            }
        }


        /// 设置汇总列信息
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var summaryFields = base.GetSummaryColumnInfo(filter);
            return summaryFields;
        }

        ///构建order by语句
        protected override string BuilderTempTableOrderBySQL(IRptParams filter)
        {
            string OrderBy = "";
            string datasort = Convert.ToString(filter.FilterParameter.SortString);//排序
            if (datasort != "")
            {
                OrderBy = datasort;
            }
            else
            {
                OrderBy = " FmodifyDate DESC ";
            }
            return OrderBy;
        }

        ////获取过滤条件
        private string GetFilterWhere(IRptParams filter)
        {
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            StringBuilder strwhere = new StringBuilder();
            strwhere.AppendLine("Where 1=1 ");

            string text2 = string.IsNullOrWhiteSpace(filter.FilterParameter.FilterString) ? " " : " AND " + filter.FilterParameter.FilterString.Replace("{ts", "").Replace("}", "");
            strwhere.AppendLine(text2);
            return strwhere.ToString();
        }

        /// <summary>
        /// 将字符串转换为in格式条件
        /// </summary>
        /// <returns></returns>
        private string ConvertInWhere(string where)
        {
            string result = "";
            result = where.Replace(",", "','");
            result = "'" + result + "'";
            return result;
        }

        public override void CloseReport()
        {
            //删除临时表
            if (!customRptTempTableNames.IsNullOrEmptyOrWhiteSpace())
            {
                IDBService dbService = Kingdee.BOS.App.ServiceHelper.GetService<IDBService>();
                bool b = dbService.DeleteTemporaryTableName(this.Context, customRptTempTableNames.ToArray());
            }
            base.CloseReport();
        }
    }
}
